package com.search.app.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.search.app.Mapper.ProductimageMapper;
import com.search.app.Service.CommoditySearchService;
import com.search.app.VO.Product;
import com.search.app.VO.Productimage;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommoditySearchServiceImpl implements CommoditySearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private ProductimageMapper productimageMapper;


    @Override
    public List<?> keyWordSearch(String keyWord) {
        Query query=new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("product_name",keyWord)).build();
        SearchHits<Product> search = elasticsearchRestTemplate.search(query, Product.class);
        List<Product> list=new ArrayList<>();
        for (SearchHit<Product> searchHits : search) {
            Product content = searchHits.getContent();
            List<Productimage> list1 = productimage_product_idSearch(content.getProduct_id());
            content.setProductimage(list1);
            list.add(content);
        }
        return list;
    }


//    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
//            .must(QueryBuilders.termQuery(Constant.XTopicIndexFields.FIELD_ALGORITHM_TAG, algorithmTag));
//        boolQueryBuilder.must(QueryBuilders.termQuery(XTopicConstant.FIELD_STATUS, status));
//        searchSourceBuilder.sort(XTopicIndexFields.FIELD_TOPIC_PUBLISH_TIME, SortOrder.DESC);
//        searchSourceBuilder.from(from).size(size).postFilter(boolQueryBuilder);
//        return query(searchSourceBuilder.toString());



    @Override
    public List<Productimage> productimage_product_idSearch(Integer product_id) {
        QueryWrapper<Productimage> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("productimage_product_id",product_id);
        List<Productimage> list = productimageMapper.selectList(queryWrapper);
        return list;
    }





}
